package staticClasses;
import players.*;

public class PlayerManager extends Thread{
	public PlayerManager(){
	}

	public void run(){
		startPlayers();
	}
	
	public void startPlayers(){
		for(Player p:Global.localTeam){
			p.start();
		}
		for(Player p:Global.visitorTeam){
			p.start();
		}
		Global.ball.start();
		
		while(Global.play){
			Global.clock++;
			
			if(Global.inArray(Global.ball.getPosition()[0],Global.ball.getPosition()[1],Global.localTeam_goalLine)){
				Global.score[1]++;
				System.out.println("But des Visiteurs. Score : "+Global.score[0]+" - "+Global.score[1]);
				goal();
			}
			else if(Global.inArray(Global.ball.getPosition()[0],Global.ball.getPosition()[1],Global.visitorTeam_goalLine)){
				Global.score[0]++;
				System.out.println("But des Locaux. Score : "+Global.score[0]+" - "+Global.score[1]);
				goal();
			}
			
			while(Global.pause){
				try{Thread.sleep(250);
				}catch(Exception e){e.printStackTrace();}
			}
			
			try{
				Thread.sleep(Global.tick);
			}catch(Exception e){
			}
			for(Player p:Global.localTeam){
				synchronized(p){
					p.notify();
				}
			}
			for(Player p:Global.visitorTeam){
				synchronized(p){
					p.notify();
				}
			}
			synchronized(Global.ball){
				Global.ball.notify();
			}
		}

		try{Thread.sleep(500);
		}catch(Exception e){e.printStackTrace();}
		
		try{
			for(Player p:Global.localTeam){
				synchronized(p){
					p.notify();
				}
			}
			for(Player p:Global.visitorTeam){
				synchronized(p){
					p.notify();
				}
			}
			synchronized(Global.ball){
				Global.ball.notify();
			}
		}catch(Exception e){}
		
		Global.visitorTeam=null;
		Global.localTeam=null;
		Global.ball=null;
		Global.setBallOwner(null);
		Global.Map=null;
		Global.score[0]=0;
		Global.score[1]=0;
		Global.clock=0;
	}
	
	public void goal(){
		for(Player p:Global.localTeam){
			p.setPosition(p.initialSpot.x, p.initialSpot.y);
			p.nextAction=Action.STAND;
			p.ballState=0;
		}
		for(Player p:Global.visitorTeam){
			p.setPosition(p.initialSpot.x, p.initialSpot.y);
			p.nextAction=Action.STAND;
			p.ballState=0;
		}
		Global.ball.setPosition(Global.center.x, Global.center.y);
		Global.ball.velocity=0;
		Global.ball.targeted_case[0]=Global.center.x;
		Global.ball.targeted_case[1]=Global.center.y;
		Global.setBallOwner(null);
	}
}
